import { login, userMeuns } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken() || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo')),
    userMeuns: []
  }
}

const state = getDefaultState()

const mutations = {
  // 保存token
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  // 保存用户信息
  setUserinfo(state, user) {
    state.userInfo = user
    localStorage.setItem('userInfo', JSON.stringify(user))
  },
  setUsermeuns(state, user) {
    state.userMeuns = user
  }
}

const actions = {
  // 退出
  logout(cxt) {
    cxt.commit('setToken', '')
    cxt.commit('setUserinfo', '')
  },
  // 登录请求
  async setLogin(cxt, data) {
    const res = await login(data)
    // console.log(res)
    cxt.commit('setToken', res.data.data.token.token)
    cxt.commit('setUserinfo', res.data.data.user)
    Message.success('登录成功!')
  },
  // 用户菜单
  async setUsermeuns(cxt) {
    const res = await userMeuns()
    console.log(res)
    cxt.commit('setUsermeuns', res)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

